import React from 'react'
import { Button, DatePicker, message, Skeleton, Empty, Modal, Form, Input } from 'antd'
import { CalendarOutlined } from '@ant-design/icons'
import moment from 'moment'
import Component, { mapStateToProps, mapDispatchToProps } from '@components/Component'
import { connect } from 'react-redux'
import Row from '@components/RoomBookList/Row'
import style from './RoomBookList.module.less'
const { Item } = Form
const { TextArea } = Input
class RoomBookList extends Component {
  state = {
    datepickerOpen: false,
    selectedDate: moment(this.formatDate(moment())),
    morningList: [],
    afternoonList: [],
    loading: false,
    cancalVisible: false,
    cancelData: null
  }

  dateRef = React.createRef()
  formRef = React.createRef()

  formatDate (date) {
    if (date instanceof moment) {
      return date.format('YYYY-MM-DD')
    }
  }

  changeDate (v) {
    this.setState({ datepickerOpen: false, selectedDate: v }, () => {
      this.setState({
        morningList: [],
        afternoonList: []
      }, () => {
        this.getList()
      })
    })
  }

  // 获取某天的庭室预约信息
  getList () {
    this.setState({ loading: true })
    const hide = message.loading('加载中', 120)
    const day = this.state.selectedDate.format('YYYY-MM-DD')
    this.$get('/api/xapc/hearingroombook/day', {
      day
    }).then(res => {
      hide()
      this.setState({ loading: false })
      if (res.status === 1) {
        const morningList = []
        const afternoonList = []
        res.data.forEach(li => {
          if (moment(li.begin_datetime * 1000).hour() >= 12) {
            afternoonList.push(li)
          } else {
            morningList.push(li)
          }
        })
        this.setState({
          morningList,
          afternoonList
        })
      } else {
        message.warning(res.message)
      }
    }).catch(() => {
      hide()
      this.setState({ loading: false })
    })
  }

  // 预约新庭室
  bookNew () {
    this.props.addWindow({ id: 'RoomBookDetail', title: '新增预约庭室', componentName: 'RoomBookDetail', forceRefresh: false, meta: { } })
  }

  // 修改约庭
  modifyHandle (d) {
    const isOther = !d.caseid
    const title = `修改预约庭室-${isOther ? d.caseno_desc_redundant : d.caseno_desc}`
    this.props.addWindow({ id: 'RoomBookDetail', title, componentName: 'RoomBookDetail', forceRefresh: false, meta: { data: d } })
  }

  // 取消约庭请求
  cancelRequest (d) {
    const hide = message.loading('取消预约中', 120)
    const o = this.state.cancelData
    this.$put(`/api/xapc/hearingroombook/${o.id}`, {
      hearingroomid: o.hearingroomid,
      begin_datetime: o.begin_datetime,
      end_datetime: o.end_datetime,
      remark: o.remark,
      use: o.use,
      cancel_remark: d.cancel_remark,
      status: 0
    }).then(res => {
      hide()
      if (res.status === 1) {
        this.setState({
          cancalVisible: false,
          cancelData: null
        }, () => {
          this.getList()
        })
      } else {
        message.warning(res.message)
      }
    }).catch(() => hide())
  }

  componentDidMount () {
    this.getList()
  }

  renderEmpty () {
    const { morningList, afternoonList, loading } = this.state
    if (!loading && morningList.length === 0 && afternoonList.length === 0) {
      return <Empty image={Empty.PRESENTED_IMAGE_SIMPLE} />
    }
  }

  // 渲染约庭列表
  renderList (list) {
    return list.map(li => {
      return <Row key={li.id} data={li} modifyHandle={(d) => this.modifyHandle(d)} cancelHandle={d => this.setState({ cancelData: d, cancalVisible: true })} />
    })
  }

  // 渲染上午列表
  renderMorning () {
    const { morningList: m } = this.state
    if (!m.length) {
      return null
    }
    return (
      <>
        <div className={style['body-title']}>上午</div>
        {this.renderList(m)}
      </>
    )
  }

  // 渲染上午列表
  renderAfternoon () {
    const { afternoonList: a } = this.state
    if (!a.length) {
      return null
    }
    return (
      <>
        <div className={style['body-title']}>下午</div>
        {this.renderList(a)}
      </>
    )
  }

  renderCancelModel () {
    return (
      <Modal
        title='取消预约'
        open={this.state.cancalVisible}
        onOk={() => this.formRef.current.submit()}
        onCancel={() => this.setState({ cancalVisible: false })}
      >
        <Form ref={this.formRef} labelCol={{ flex: '80px' }} onFinish={d => this.cancelRequest(d)}>
          <Item label='取消原因' name='cancel_remark' rules={[{ required: true, message: '取消原因不能为空' }]}>
            <TextArea placeholder='请输入取消原因' rows={4} />
          </Item>
        </Form>
      </Modal>
    )
  }

  render () {
    return (
      <div className={style.container}>
        {this.renderCancelModel()}
        <div className={style['title-line']}>
          <span className={style['title-left']}>
            <span className={style['title-text']}>{this.props.title}</span>
            <label className={style['header-date']}>
              <span className={style['header-date-text']}>{this.formatDate(this.state.selectedDate)}</span>
              <span className={style.datepicker}>
                <DatePicker value={this.state.selectedDate} ref={this.dateRef} inputReadOnly open={this.state.datepickerOpen} onChange={v => this.changeDate(v)} onFocus={() => this.setState({ datepickerOpen: true })} onBlur={() => this.setState({ datepickerOpen: false })} />
              </span>
              <CalendarOutlined className={style['calendar-icon']} />
            </label>
          </span>
          <Button type='primary' onClick={() => this.bookNew()}>预约庭室</Button>
        </div>
        <div className={style.body}>
          {this.renderMorning()}
          {this.renderAfternoon()}
          {this.renderEmpty()}
          {this.state.loading ? (<div className={style['loading-box']}><Skeleton /></div>) : null}
        </div>
      </div>
    )
  }
}

const mapState = mapStateToProps(function (state) {
  return {
    userInfo: state.basic.userInfo
  }
})

const mapDispatch = mapDispatchToProps(function (dispatch) {
  return {
  }
})

export default connect(mapState, mapDispatch)(RoomBookList)
